package com.gin.kotlin.no_gay_alliance.base

import android.database.Cursor
import android.net.Uri
import android.provider.MediaStore
import androidx.core.database.getStringOrNull
import androidx.fragment.app.FragmentActivity
import java.io.File

fun Cursor.readStringOrNull(column: String) = this.getStringOrNull(this.getColumnIndex(column))

data class ContentFile(
    var uri: Uri,
    var originalName: String? = null,
    var size: Int? = null,
    var ext: String? = null,
    var mimeType: String? = null,
) {
    /**
     * 从URI中读取文件信息
     * @param uri Uri
     * @param fragmentActivity FragmentActivity
     * @constructor
     */
    constructor(uri: Uri, fragmentActivity: FragmentActivity) : this(uri) {
        val contentResolver = fragmentActivity.contentResolver
        val cursor = contentResolver.query(uri, null, null, null, null)?.also { it.moveToFirst() } ?: return

        this.originalName = cursor.readStringOrNull(MediaStore.Files.FileColumns.DISPLAY_NAME)
        this.mimeType = cursor.readStringOrNull(MediaStore.Files.FileColumns.MIME_TYPE)
        this.size = cursor.readStringOrNull(MediaStore.Files.FileColumns.SIZE)?.toIntOrNull()
        this.ext = this.originalName?.let { File(it).extension } ?: this.mimeType?.split("/")?.get(1)
        cursor.close()
    }
}